package com.coding.mybatis;

import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.Setter;

/**
 * @ClassName GenericTokenParser
 * @Author ykx
 * @Date 2023/12/31 16:49
 * @Version 1.0
 */
@AllArgsConstructor
@Getter
@Setter
public class GenericTokenParser {

    /**
     * 开始
     */
    private String begin;

    /**
     * 结束
     */
    private String end;

    /**
     * parameterMappingTokenHandler
     */
    private ParameterMappingTokenHandler parameterMappingTokenHandler;

    public String parse(String sql) {
        StringBuilder builder = new StringBuilder();

        // 查找开始标记的下标
        int beginIndex = sql.indexOf(begin);

        // 查找结尾标记的下标
        int endIndex = sql.indexOf(end, beginIndex);

        int offset = 0;

        while (beginIndex != -1) {
            // 拼接处理完的部分
            builder.append(sql, offset, beginIndex);

            // 调用参数映射标记处理器
            builder.append(parameterMappingTokenHandler
                    .handleToken(sql.substring(beginIndex + begin.length(), endIndex)));
            offset = endIndex + end.length();
            beginIndex = sql.indexOf(begin, endIndex);
            endIndex = sql.indexOf(end, beginIndex);
        }

        builder.append(sql.substring(offset));

        return builder.toString();
    }

}
